"use strict"

var Router = require('koa-router');
var config = require('../../../config/config.js');
var dao = require('../../../dao/mongo/vendor.js');

console.log('router:' + config.baseUrl + '/v1/vendor');

var router = new Router({
    prefix: config.baseUrl + '/v1/vendor'
});

router.get('/test', function*() {
    this.body = 'test work fine';
});


// 添加用户
router.post('/', function*() {
    var result = yield dao.save(this.request.inParams);
    this.body = result;
});

// 
router.post('/login', function*() {
    var inParams = this.request.inParams;
    if (inParams.email && inParams.password) {
        var result = yield dao.check(this.request.inParams);
        console.log(result);
        if (result) {
            console.log('login success, add session,id=' + result._id);
            this.session.vendorId = result._id;
            this.body = 'ok';
            return;
        }
    }

    this.status = 401;
    this.body = 'wrong password or email 22';
});

router.post('/register', function*() {
    var inParams = this.request.inParams;
    var errMsg;
    if (inParams.email && inParams.password && inParams.name) {
        var result = yield dao.save(this.request.inParams);
        if (!result.errCode) {
            this.status = 200;
            this.body = 'OK';
            return;
        }
        errMsg = result.errMsg;
    }

    this.status = 401;
    this.body = errMsg;
});

// 获取用户信息
router.get('/:id', function*() {
    var result = yield dao.findById(this.params.id);
    this.body = result;
});

module.exports = router.routes();